from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from .serializers import AreaSerializer, SubAreaSerializer
from .models import Area

# Create your views here.

# 三级联动视图
class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    '''
    返回省市数据
    '''
    #　怕如果省市列表中的项过多默认会分页，所以需要关闭分页
    pagination_class = None

    # 按照路由中行为返回不同的序列化器
    def get_serializer_class(self):
        # 如果请求的是ｌｉｓｔ　反回所有的省
        if self.action == "list":
            return AreaSerializer
        else:
            return SubAreaSerializer

    def get_queryset(self):
        if self.action == "list":
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()


